const ShareModel = require('../model/share')
const UserModel = require('../model/user')
const Common = require('../util/common')
const Constant = require('../constant/constant')
const moment = require('moment');
const db = require('../db');
const LikeModel = require('../model/like');
const { Op } = require("sequelize");
const RemarkModel = require('../model/remark');
const CollectModel = require('../model/collect')




let exportObj = {
    createShare,
    getShareById,
    getShare,
    getGuideSearch
};
// 导出对象，供其它模块调用
module.exports = exportObj;

//将数据库拿出的图片地址字符串转化成数组
function getImgList(image) {
    return image.split("|")
}
//创建动态
async function createShare(req, res) {
    // 定义一个返回对象
    if (Common.check(req.body, ['title', 'content', 'imageList']) === false) {
        res.json(Constant.LACK)
    } else {
        const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
        let image = '';
        req.body.imageList.forEach((element, index) => {
            image = image + element + '|'
        });
        image = image.slice(0, image.length - 1)
        try {
            const result = await ShareModel.create({
                u_id: req.user.id,
                title: req.body.title,
                content: req.body.content,
                image: image,
                like: 0,
                collected: 0,
                created_at: moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'),
                updated_at: moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')
            })
            console.log(result)
            if (result.id) {
                res.json(resObj)
            } else {
                res.json(Constant.DEFAULT_ERROR)
            }
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }
    }
}

//根据ID获取动态
async function getShareById(req, res) {
    // 定义一个返回对象
    if (Common.check(req.query, ['s_id']) === false) {
        res.json(Constant.LACK)
    } else {
        const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
        try {
            ShareModel.belongsTo(UserModel, { foreignKey: 'u_id' })
            RemarkModel.belongsTo(UserModel, { foreignKey: 'u_id' })
            const result = await ShareModel.findOne({
                where: {
                    id: req.query.s_id
                },
                include: {
                    model: UserModel
                }
            })
            const result1 = await RemarkModel.findAll({
                where: {
                    s_id: req.query.s_id,
                    r_id:{
                        [Op.is]:null
                    }
                },
                include: {
                    model: UserModel
                }
            })
            const test = await LikeModel.findAll({
                where: {
                    u_id: req.user.id,
                    r_id: {
                        [Op.not]: null
                    }
                }
            })
            test.forEach((item, index) => {
                test[index] = item.r_id
            })
            result1.forEach(item => {
                if (test.includes(item.id)) {
                    item.dataValues.isLike = 1
                } else {
                    item.dataValues.isLike = 0
                }
            })
            if (!!result) {
                result.image = getImgList(result.image)
                result.dataValues.remark = result1


                //检测点赞，收藏
                const test1 = await CollectModel.findOne({
                    where: {
                        s_id: req.query.s_id,
                        u_id: req.user.id
                    }
                })
                if (!!test1) {
                    result.dataValues.isCollect = 1
                } else {
                    result.dataValues.isCollect = 0
                }

                const test2 = await LikeModel.findOne({
                    where: {
                        s_id: req.query.s_id,
                        u_id: req.user.id
                    }
                })
                if (!!test2) {
                    result.dataValues.isLike = 1
                } else {
                    result.dataValues.isLike = 0
                }
                resObj.data = result
                res.json(resObj)
            } else {
                res.json(Constant.DEFAULT_ERROR)
            }
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }
    }
}

//动态分页获取
async function getShare(req, res) {
    // 定义一个返回对象
    if (Common.check(req.query, ['page', 'limit']) === false) {
        res.json(Constant.LACK)
    } else {
        const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
        try {
            return await db.transaction(async (t) => {
                ShareModel.belongsTo(UserModel, { foreignKey: 'u_id' })
                let result = await ShareModel.findAll({
                    offset: (req.query.page - 1) * req.query.limit,
                    limit: parseInt(req.query.limit),
                    include: {
                        model: UserModel
                    }
                }, { transaction: t })

                let likeArr = await LikeModel.findAll({
                    attributes: ['s_id'],
                    where: {
                        u_id: req.user.id,
                        s_id: {
                            [Op.not]: null,
                        }
                    }
                })
                likeArr.forEach((item, index) => {
                    likeArr[index] = item.s_id
                })
                result.forEach((element, index) => {
                    if (likeArr.includes(element.id)) {
                        result[index].dataValues.isLike = 1
                    } else {
                        result[index].dataValues.isLike = 0
                    }
                    element.image = getImgList(element.image)
                });
                resObj.data = result
                res.json(resObj)
            });
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }
    }
}

//模糊查询分页获取
async function getGuideSearch(req, res) {
    // 定义一个返回对象
    if (Common.check(req.query, ['page', 'limit', 'guide']) === false) {
        res.json(Constant.LACK)
    } else {
        const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
        try {
            return await db.transaction(async (t) => {
                ShareModel.belongsTo(UserModel, { foreignKey: 'u_id' })
                let result = await ShareModel.findAll({
                    offset: (req.query.page - 1) * req.query.limit,
                    limit: parseInt(req.query.limit),
                    where: {
                        [Op.or]: [{
                            title: {
                                [Op.like]: '%' + req.query.guide + '%',
                            }
                        }, {
                            content: {
                                [Op.like]: '%' + req.query.guide + '%',
                            }
                        }],
                    },
                    include: {
                        model: UserModel
                    }
                }, { transaction: t })

                let likeArr = await LikeModel.findAll({
                    attributes: ['s_id'],
                    where: {
                        u_id: req.user.id,
                        s_id: {
                            [Op.not]: null,
                        }
                    }
                })
                likeArr.forEach((item, index) => {
                    likeArr[index] = item.s_id
                })
                result.forEach((element, index) => {
                    if (likeArr.includes(element.id)) {
                        result[index].dataValues.isLike = 1
                    } else {
                        result[index].dataValues.isLike = 0
                    }
                    element.image = getImgList(element.image)
                });
                resObj.data = result
                res.json(resObj)
            });
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }
    }
}